package com.bigshark.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bigshark.api.form.LoginForm;
import com.bigshark.api.form.RegisterForm;
import com.bigshark.api.mapper.UserMapper;
import com.bigshark.api.model.User;
import com.bigshark.api.model.UserToken;
import com.bigshark.api.service.UserService;
import com.bigshark.common.exception.AmineException;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {
    @Autowired
    private UserTokenServiceImpl userTokenService;

    private User selectByUserName(String username){
        return baseMapper.selectOne(new QueryWrapper<User>().eq("user_name",username));
    }

    @Override
    public Map<String,Object> login(LoginForm login, HttpServletRequest request) {
        User user = selectByUserName(login.getUsername());
        Assert.notNull(user,"账户不存在");
        if(!user.getPassword().equals(DigestUtils.sha256Hex(login.getPassword()))){
            throw new AmineException("密码错误");
        }
        user.setPassword("");
        Map<String,Object> data = new HashMap<>();
        UserToken userToken = userTokenService.createToken(user.getId(),request);
        Assert.notNull(user,"token生成失败");
        user.setToken(userToken.getToken());
        data.put("data",user);
        return data;
    }


    @Override
    public void register(RegisterForm registerForm) {
        User user = selectByUserName(registerForm.getUname());
        Assert.isNull(user,"该用户名已注册");
        if(!registerForm.getPasswd().equals(registerForm.getRePasswd())){
            throw new AmineException("两次密码不一致");
        }
        User u = new User();
        u.setUserName(registerForm.getUname());
        u.setRole(registerForm.getRole());
        u.setPassword(DigestUtils.sha256Hex(registerForm.getPasswd()));
        baseMapper.insert(u);

    }
}
